<template>
  <header class="header">
    <svg
      style="position: absolute; width: 0; height: 0; overflow: hidden;"
      version="1.1"
      xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink"
    >
      <defs>
        <symbol id="icon-arrow-short" viewBox="0 0 25 32">
          <title>arrow-short</title>
          <path
            class="path1"
            d="M24.487 18.922l-1.948-1.948-8.904 8.904v-25.878h-2.783v25.878l-8.904-8.904-1.948 1.948 12.243 12.243z"
          ></path>
        </symbol>
        <symbol id="icon-status-ok" viewBox="0 0 32 32">
          <title>status-ok</title>
          <path
            class="path1"
            d="M22.361 10.903l-9.71 9.063-2.998-2.998c-0.208-0.209-0.546-0.209-0.754 0s-0.208 0.546 0 0.754l3.363 3.363c0.104 0.104 0.241 0.156 0.377 0.156 0.131 0 0.261-0.048 0.364-0.143l10.087-9.414c0.215-0.201 0.227-0.539 0.026-0.754s-0.539-0.226-0.754-0.026z"
          ></path>
          <path
            class="path2"
            d="M16 30.933c-8.234 0-14.933-6.699-14.933-14.933s6.699-14.933 14.933-14.933c8.234 0 14.933 6.699 14.933 14.933s-6.699 14.933-14.933 14.933zM16 0c-8.822 0-16 7.178-16 16 0 8.823 7.178 16 16 16s16-7.177 16-16c0-8.822-7.178-16-16-16z"
          ></path>
        </symbol>
        <symbol id="icon-cart" viewBox="0 0 38 32">
          <title>cart</title>
          <path
            class="path1"
            d="M37.759 0h-4.133c-0.733 0.004-1.337 0.549-1.434 1.255l-0.546 4.342c-0.081 0.484-0.496 0.849-0.997 0.849-0.005 0-0.009-0-0.014-0h-27.604c-0.003 0-0.007-0-0.011-0-1.674 0-3.031 1.357-3.031 3.031 0 0.34 0.056 0.666 0.159 0.971l2.52 8.062c0.385 1.194 1.486 2.043 2.785 2.043 0.126 0 0.25-0.008 0.372-0.023l22.983 0.002c0.515 0.131 0.626 0.768 0.626 1.283 0.005 0.044 0.009 0.095 0.009 0.146 0 0.501-0.294 0.933-0.718 1.134l-22.439 0.003c-0.354 0-0.642 0.287-0.642 0.642s0.287 0.642 0.642 0.642h22.745l0.131-0.071c0.919-0.392 1.551-1.287 1.551-2.33 0-0.058-0.002-0.116-0.006-0.173 0.021-0.108 0.033-0.24 0.033-0.376 0-1.072-0.732-1.973-1.724-2.23l-23.357-0.004c-0.063 0.008-0.135 0.013-0.209 0.013-0.719 0-1.332-0.455-1.566-1.093l-2.53-8.095c-0.048-0.154-0.076-0.332-0.076-0.515 0-0.973 0.782-1.764 1.752-1.778h27.657c1.159-0.004 2.112-0.883 2.232-2.011l0.547-4.345c0.010-0.083 0.078-0.147 0.161-0.152l4.133-0c0.354 0 0.642-0.287 0.642-0.642s-0.287-0.642-0.642-0.642z"
          ></path>
          <path
            class="path2"
            d="M31.323 9.69c-0.022-0.003-0.048-0.004-0.074-0.004-0.328 0-0.598 0.248-0.633 0.567l-0.809 7.268c-0.003 0.022-0.004 0.048-0.004 0.074 0 0.328 0.248 0.598 0.567 0.633l0.074 0c0.001 0 0.003 0 0.004 0 0.327 0 0.596-0.246 0.632-0.563l0.809-7.268c0.003-0.022 0.004-0.048 0.004-0.074 0-0.328-0.248-0.598-0.567-0.633z"
          ></path>
          <path
            class="path3"
            d="M27.514 25.594c-1.769 0-3.203 1.434-3.203 3.203s1.434 3.203 3.203 3.203c1.769 0 3.203-1.434 3.203-3.203s-1.434-3.203-3.203-3.203zM27.514 30.717c-1.060 0-1.92-0.86-1.92-1.92s0.86-1.92 1.92-1.92c1.060 0 1.92 0.86 1.92 1.92s-0.86 1.92-1.92 1.92z"
          ></path>
          <path
            class="path4"
            d="M9.599 25.594c-1.769 0-3.203 1.434-3.203 3.203s1.434 3.203 3.203 3.203c1.769 0 3.203-1.434 3.203-3.203s-1.434-3.203-3.203-3.203zM9.599 30.717c-1.060 0-1.92-0.86-1.92-1.92s0.86-1.92 1.92-1.92c1.060 0 1.92 0.86 1.92 1.92s-0.86 1.92-1.92 1.92z"
          ></path>
        </symbol>
      </defs>
    </svg>
    <div class="navbar">
      <div class="navbar-left-container">
        <a href="/">
          <img class="navbar-brand-logo" src="../../static/logo.png"
        /></a>
      </div>
      <div class="navbar-right-container" style="display: flex;">
        <div class="navbar-menu-container">
          <!--用户名-->
          <span class="navbar-link" v-text="nickName" v-if="nickName"></span>

          <a
            href="javascript:void(0)"
            class="navbar-link"
            @click="Login"
            v-if="!nickName"
            >Login</a
          >
          <a
            href="javascript:void(0)"
            class="navbar-link"
            v-else
            @click="logout"
            >Logout</a
          >

          <div class="navbar-cart-container">
            <span class="navbar-cart-count" v-if="nickName === userName">{{
              countCart
            }}</span>
            <a class="navbar-link navbar-cart-link" @click="showCarts">
              <svg class="navbar-cart-logo">
                <use
                  xmlns:xlink="http://www.w3.org/1999/xlink"
                  xlink:href="#icon-cart"
                ></use>
              </svg>
            </a>
          </div>
        </div>
      </div>
    </div>
    <!-- 登陆弹框 -->

    <el-dialog
      title="登陆"
      @close="closeDialog"
      :visible.sync="loginDialogVisible"
      width="500px"
    >
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginFormRules"
        label-width="8px"
        class="login_form"
      >
        <!-- 用户名 -->
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            prefix-icon="iconfont icon-user"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="userPwd">
          <el-input
            type="password"
            v-model="loginForm.userPwd"
            prefix-icon="iconfont icon-3702mima"
          ></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="checkLogin">登陆</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </header>
</template>
<script>
import './../assets/css/login.css'
import { mapState, mapMutations } from 'vuex'
import qs from 'qs'
export default {
  data() {
    return {
      //控制登陆弹框的显示与隐藏
      loginDialogVisible: this.showLoginFlag,
      //登陆表单
      loginForm: {
        userName: 'admin',
        userPwd: '123456'
      },
      //这是表单的验证规则对象
      loginFormRules: {
        //验证用户名是否合法
        userName: [
          { required: true, message: '请输入用户名称!', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在 3 到 10 个字符!',
            trigger: 'blur'
          }
        ],
        //验证面是否合法
        userPwd: [
          { required: true, message: '请输入密码!', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在 6 到 15 个字符!',
            trigger: 'blur'
          }
        ]
      },
      //控制logout的显示与隐藏
      //显示登陆的用户名
      nickName: '',
      userName: '',
      //购物车数量
      goodsNum: 0
    }
  },
  mounted() {
    //校验登陆状态
    this.checkkLoginStatus()
  },
  methods: {
    login() {
      //显示登陆弹框
      this.loginDialogVisible = true
    },
    //监听弹框的关闭事件
    closeDialog() {
      //重置表单
      this.resetLoginForm()
    },
    //点击重置登陆表单
    resetLoginForm() {
      // console.log(this);
      //调用resetFields重置表单
      this.$refs.loginFormRef.resetFields()
    },
    //表单预校验
    checkLogin() {
      //调用validate进行预校验,参数是一个回到函数，返回一个布尔值，校验成功为true
      this.$refs.loginFormRef.validate(valid => {
        if (valid) {
          this.$axios
            .post('/users/login', qs.stringify(this.loginForm))
            .then(res => {
              console.log(res)
              if (res.status !== 200) return this.$message.error(res.msg)
              //登陆成功
              this.$message.success(res.msg)
              //显示用户名和退出按钮还有购物车中的数量
              this.nickName = res.data.userName
              this.userName = res.data.userName
              //把返回的用户id和用户名存储在cookie中
              this.$cookies.set('userId', res.data.userId, 60 * 60) //设置一小时过期
              this.$cookies.set('userName', res.data.userName, 60 * 60)
              //隐藏对话框
              this.loginDialogVisible = false
              //显示购物车的商品数量
              this.getGoodsNum()
            })
            .catch(err => console.log(err))
        }
      })
    },
    //显示购物车的商品数量
    getGoodsNum() {
      const userId = this.$cookies.get('userId')
      //显示购物车的商品数量
      this.$axios
        .get('/carts/getCarts', {
          params: {
            userId
          }
        })
        .then(res => {
          console.log(res)
          this.goodsNum = res.data.goodsNum
          this.$store.commit('countCartNum', this.goodsNum)
        })
        .catch(err => console.log(err))
    },
    //显示登陆弹框
    Login() {
      this.loginDialogVisible = true
    },
    //退出
    logout() {
      this.$confirm('你确定要退出吗？', '退出提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios.post('/users/logout').then(res => {
            this.$message.success(res.msg)
            //清除cookies
            this.$cookies.remove('userId')
            this.$cookies.remove('userName')
            //让nickname为空
            this.nickName = ''
            //跳转到商品列表页面
            this.$router.push('/goodList').catch(err => err)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '祝您购物愉快!'
          })
        })
    },
    //校验登陆状态
    checkkLoginStatus() {
      //获取cookie
      this.userName = this.$cookies.get('userName')
      const userId = this.$cookies.get('userId')
      //判断是否有用户名和用户ID
      if (this.userName && userId) {
        //处于登陆状态，显示用户名和logout
        this.nickName = this.userName
        // console.log(this.nickName)
        //显示购物车的商品数量
        this.getGoodsNum()
      } else {
        //如果没有登陆，跳转到商品列表
        this.$router.push('/goodList').catch(err => {
          err
        })
      }
    },
    //点击购物车图标触发
    showCarts() {
      //判断用户是否已登录
      //获取cookie
      const userName = this.$cookies.get('userName')
      const userId = this.$cookies.get('userId')
      if (userName && userId) {
        //证明用户已经登陆
        //跳转到购物车页面
        this.$router.push('/cart')
      } else {
        //用户没有登陆
        this.$confirm('您还没有登陆，无法查看购物车呢!', '提示', {
          confirmButtonText: '点我登陆',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            //显示登陆弹框
            this.loginDialogVisible = true
          })
          .catch(() => {
            this.$message.info('请先登陆再查看购物车哦亲!')
          })
        //跳转到
      }
    }
  },
  computed: {
    ...mapState(['countCart'])
  }
}
</script>
<style scoped>
.btns {
  padding-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.header {
  width: 100%;
  background-color: white;
  font-family: 'moderat', sans-serif;
  font-size: 16px;
}
.navbar {
  display: flex;
  justify-content: space-between;
  align-content: center;
  width: 100%;
  height: 70px;
  max-width: 1280px;
  margin: 0 auto;
  padding: 5px 20px 10px 20px;
}
.navbar-left-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-left: -20px;
}
.navbar-brand-logo {
  /*width: 120px;*/
}
.header a,
.footer a {
  color: #666;
  text-decoration: none;
}
a {
  -webkit-transition: color 0.3s ease-out;
  transition: color 0.3s ease-out;
}
.navbar-right-container {
  display: none;
  justify-content: flex-start;
  align-items: center;
}
.navbar-menu-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 10px;
}
.navbar-link {
  padding-left: 15px;
}
.navbar-cart-container {
  position: relative;
}
.navbar-cart-count {
  justify-content: center;
  align-items: center;
  position: absolute;
  top: -9px;
  right: -11px;
  width: 28px;
  border-radius: 10px;
  color: white;
  background-color: #eb767d;
  font-size: 1px;
  font-weight: bold;
  text-align: center;
}
.navbar-cart-logo {
  width: 25px;
  height: 25px;
  transform: scaleX(-1);
}
</style>
